package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.equipmentinfo.EquipmentInfoAddRequest;
import com.cyy.springbootinit.model.dto.equipmentinfo.EquipmentInfoEditRequest;
import com.cyy.springbootinit.model.dto.equipmentinfo.EquipmentInfoQueryRequest;
import com.cyy.springbootinit.model.dto.equipmentinfo.EquipmentInfoUpdateRequest;
import com.cyy.springbootinit.model.entity.EquipmentInfo;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.EquipmentInfoVO;
import com.cyy.springbootinit.service.EquipmentInfoService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 设备信息表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/equipmentInfo")
@Slf4j
public class EquipmentInfoController {

    @Resource
    private EquipmentInfoService equipmentInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建设备信息表
     *
     * @param equipmentInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addEquipmentInfo(@RequestBody EquipmentInfoAddRequest equipmentInfoAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(equipmentInfoAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentInfo equipmentInfo = new EquipmentInfo();
        BeanUtils.copyProperties(equipmentInfoAddRequest, equipmentInfo);
        // 数据校验
        equipmentInfoService.validEquipmentInfo(equipmentInfo, true);
        // todo 填充默认值
        // 写入数据库
        boolean result = equipmentInfoService.save(equipmentInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newEquipmentInfoId = equipmentInfo.getEquipmentId();
        return ResultUtils.success(newEquipmentInfoId);
    }

    /**
     * 删除设备信息表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteEquipmentInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        EquipmentInfo oldEquipmentInfo = equipmentInfoService.getById(id);
        ThrowUtils.throwIf(oldEquipmentInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldEquipmentInfo.getEquipmentId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = equipmentInfoService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新设备信息表（仅管理员可用）
     *
     * @param equipmentInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateEquipmentInfo(@RequestBody EquipmentInfoUpdateRequest equipmentInfoUpdateRequest) {
        if (equipmentInfoUpdateRequest == null || equipmentInfoUpdateRequest.getEquipmentId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentInfo equipmentInfo = new EquipmentInfo();
        BeanUtils.copyProperties(equipmentInfoUpdateRequest, equipmentInfo);
        // 数据校验
        equipmentInfoService.validEquipmentInfo(equipmentInfo, false);
        // 判断是否存在
        long id = equipmentInfoUpdateRequest.getEquipmentId();
        EquipmentInfo oldEquipmentInfo = equipmentInfoService.getById(id);
        ThrowUtils.throwIf(oldEquipmentInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = equipmentInfoService.updateById(equipmentInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取设备信息表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<EquipmentInfoVO> getEquipmentInfoVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        EquipmentInfo equipmentInfo = equipmentInfoService.getById(id);
        ThrowUtils.throwIf(equipmentInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(equipmentInfoService.getEquipmentInfoVO(equipmentInfo, request));
    }

    /**
     * 分页获取设备信息表列表（仅管理员可用）
     *
     * @param equipmentInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<EquipmentInfo>> listEquipmentInfoByPage(@RequestBody EquipmentInfoQueryRequest equipmentInfoQueryRequest) {
        long current = equipmentInfoQueryRequest.getCurrent();
        long size = equipmentInfoQueryRequest.getPageSize();
        // 查询数据库
        Page<EquipmentInfo> equipmentInfoPage = equipmentInfoService.page(new Page<>(current, size),
                equipmentInfoService.getQueryWrapper(equipmentInfoQueryRequest));
        return ResultUtils.success(equipmentInfoPage);
    }

    /**
     * 分页获取设备信息表列表（封装类）
     *
     * @param equipmentInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<EquipmentInfoVO>> listEquipmentInfoVOByPage(@RequestBody EquipmentInfoQueryRequest equipmentInfoQueryRequest,
                                                               HttpServletRequest request) {
        long current = equipmentInfoQueryRequest.getCurrent();
        long size = equipmentInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<EquipmentInfo> equipmentInfoPage = equipmentInfoService.page(new Page<>(current, size),
                equipmentInfoService.getQueryWrapper(equipmentInfoQueryRequest));
        // 获取封装类
        return ResultUtils.success(equipmentInfoService.getEquipmentInfoVOPage(equipmentInfoPage, request));
    }

    /**
     * 分页获取当前登录用户创建的设备信息表列表
     *
     * @param equipmentInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<EquipmentInfoVO>> listMyEquipmentInfoVOByPage(@RequestBody EquipmentInfoQueryRequest equipmentInfoQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(equipmentInfoQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        long current = equipmentInfoQueryRequest.getCurrent();
        long size = equipmentInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<EquipmentInfo> equipmentInfoPage = equipmentInfoService.page(new Page<>(current, size),
                equipmentInfoService.getQueryWrapper(equipmentInfoQueryRequest));
        // 获取封装类
        return ResultUtils.success(equipmentInfoService.getEquipmentInfoVOPage(equipmentInfoPage, request));
    }

    /**
     * 编辑设备信息表（给用户使用）
     *
     * @param equipmentInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editEquipmentInfo(@RequestBody EquipmentInfoEditRequest equipmentInfoEditRequest, HttpServletRequest request) {
        if (equipmentInfoEditRequest == null || equipmentInfoEditRequest.getEquipmentId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentInfo equipmentInfo = new EquipmentInfo();
        BeanUtils.copyProperties(equipmentInfoEditRequest, equipmentInfo);
        // 数据校验
        equipmentInfoService.validEquipmentInfo(equipmentInfo, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = equipmentInfoEditRequest.getEquipmentId();
        EquipmentInfo oldEquipmentInfo = equipmentInfoService.getById(id);
        ThrowUtils.throwIf(oldEquipmentInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldEquipmentInfo.getEquipmentId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = equipmentInfoService.updateById(equipmentInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
